<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="每天进步一点点(node.js, javasctipt, vue, vuex, react, redux, mobx, less, sass...)">
    <meta name="keyword" content="">
    <link rel="shortcut icon" href="/img/ironman-draw.png">
    <!-- Place this tag in your head or just before your close body tag. -->
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <title>
        
          immutable.js 在redux项目中实践 - undefined
        
    </title>

    <link rel="canonical" href="http://yoursite.com/2018/11/21/immutableJS/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS --> 
    <link rel="stylesheet" href="/css/beantech.min.css">
    
    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css">

    <link rel="stylesheet" href="/css/widget.css">

    <link rel="stylesheet" href="/css/rocket.css">

    <link rel="stylesheet" href="/css/signature.css">

    <link rel="stylesheet" href="/css/toc.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">
	<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        
            background-image: url('')
            /*post*/
        
    }
    
</style>

<header class="intro-header">
    <!-- Signature -->
    <div id="signature">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                
                    <div class="post-heading">
                        <div class="tags">
                            
                        </div>
                        <h1>immutable.js 在redux项目中实践</h1>
                        <h2 class="subheading"></h2>
                        <span class="meta">
                            Posted by eason.L on
                            2018-11-21
                        </span>
                    </div>
                


                </div>
            </div>
        </div>
    </div>
</header>

	
    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">打不死的狒狒</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/">Home</a>
                    </li>

                    

                        
                    

                        
                    

                        
                    

                        
                    

                        
                        <li>
                            <a href="/tags/">tags</a>
                        </li>
                        
                    
                    
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    <!-- Modify by Yu-Hsuan Yen -->

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

            <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

                <h3 id="immutable-js主要有三大特性："><a href="#immutable-js主要有三大特性：" class="headerlink" title="immutable.js主要有三大特性："></a>immutable.js主要有三大特性：</h3><ul>
<li>Persistent data structure （持久化数据结构）</li>
<li>structural sharing （结构共享）</li>
<li>support lazy operation （惰性操作）</li>
</ul>
<h3 id="常用api"><a href="#常用api" class="headerlink" title="常用api"></a>常用api</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Map()  原生object转Map对象 (只会转换第一层，注意和fromJS区别)</span></span><br><span class="line">immutable.Map(&#123;<span class="attr">name</span>:<span class="string">'danny'</span>, <span class="attr">age</span>:<span class="number">18</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//List()  原生array转List对象 (只会转换第一层，注意和fromJS区别)</span></span><br><span class="line">immutable.List([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>])</span><br><span class="line"></span><br><span class="line"><span class="comment">//fromJS()   原生js转immutable对象  (深度转换，会将内部嵌套的对象和数组全部转成immutable)</span></span><br><span class="line">immutable.fromJS([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>])    <span class="comment">//将原生array  --&gt; List</span></span><br><span class="line">immutable.fromJS(&#123;<span class="attr">name</span>:<span class="string">'danny'</span>, <span class="attr">age</span>:<span class="number">18</span>&#125;)   <span class="comment">//将原生object  --&gt; Map</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//toJS()  immutable对象转原生js  (深度转换，会将内部嵌套的Map和List全部转换成原生js)</span></span><br><span class="line">immutableData.toJS();</span><br><span class="line"></span><br><span class="line"><span class="comment">//查看List或者map大小  </span></span><br><span class="line">immutableData.size  或者 immutableData.count()</span><br><span class="line"></span><br><span class="line"><span class="comment">// is()   判断两个immutable对象是否相等</span></span><br><span class="line">immutable.is(imA, imB);</span><br><span class="line"></span><br><span class="line"><span class="comment">//merge()  对象合并</span></span><br><span class="line"><span class="keyword">var</span> imA = immutable.fromJS(&#123;<span class="attr">a</span>:<span class="number">1</span>,<span class="attr">b</span>:<span class="number">2</span>&#125;);</span><br><span class="line"><span class="keyword">var</span> imA = immutable.fromJS(&#123;<span class="attr">c</span>:<span class="number">3</span>&#125;);</span><br><span class="line"><span class="keyword">var</span> imC = imA.merge(imB);</span><br><span class="line"><span class="built_in">console</span>.log(imC.toJS())  <span class="comment">//&#123;a:1,b:2,c:3&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//增删改查（所有操作都会返回新的值，不会修改原来值）</span></span><br><span class="line"><span class="keyword">var</span> immutableData = immutable.fromJS(&#123;</span><br><span class="line">  a:<span class="number">1</span>,</span><br><span class="line">  b:<span class="number">2</span>，</span><br><span class="line">  c:&#123;</span><br><span class="line">    d:<span class="number">3</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">var</span> data1 = immutableData.get(<span class="string">'a'</span>) <span class="comment">//  data1 = 1  </span></span><br><span class="line"><span class="keyword">var</span> data2 = immutableData.getIn([<span class="string">'c'</span>, <span class="string">'d'</span>]) <span class="comment">// data2 = 3   getIn用于深层结构访问</span></span><br><span class="line"><span class="keyword">var</span> data3 = immutableData.set(<span class="string">'a'</span> , <span class="number">2</span>);   <span class="comment">// data3中的 a = 2</span></span><br><span class="line"><span class="keyword">var</span> data4 = immutableData.setIn([<span class="string">'c'</span>, <span class="string">'d'</span>], <span class="number">4</span>);   <span class="comment">//data4中的 d = 4</span></span><br><span class="line"><span class="keyword">var</span> data5 = immutableData.update(<span class="string">'a'</span>,<span class="function"><span class="keyword">function</span>(<span class="params">x</span>)</span>&#123;<span class="keyword">return</span> x+<span class="number">4</span>&#125;)   <span class="comment">//data5中的 a = 5</span></span><br><span class="line"><span class="keyword">var</span> data6 = immutableData.updateIn([<span class="string">'c'</span>, <span class="string">'d'</span>],<span class="function"><span class="keyword">function</span>(<span class="params">x</span>)</span>&#123;<span class="keyword">return</span> x+<span class="number">4</span>&#125;)   <span class="comment">//data6中的 d = 7</span></span><br><span class="line"><span class="keyword">var</span> data7 = immutableData.delete(<span class="string">'a'</span>)   <span class="comment">//data7中的 a 不存在</span></span><br><span class="line"><span class="keyword">var</span> data8 = immutableData.deleteIn([<span class="string">'c'</span>, <span class="string">'d'</span>])   <span class="comment">//data8中的 d 不存在</span></span><br></pre></td></tr></table></figure>
<h3 id="immutable-js的优缺点"><a href="#immutable-js的优缺点" class="headerlink" title="immutable.js的优缺点"></a>immutable.js的优缺点</h3><ul>
<li>优点<ul>
<li>降低mutable带来的复杂度</li>
<li>节省内存</li>
<li>历史追溯性（时间旅行）：时间旅行指的是，每时每刻的值都被保留了，想回退到哪一步只要简单的将数据取出就行，想一下如果现在页面有个撤销的操作，撤销前的数据被保留了，只需要取出就行，这个特性在redux或者flux中特别有用</li>
<li>拥抱函数式编程：immutable本来就是函数式编程的概念，纯函数式编程的特点就是，只要输入一致，输出必然一致，相比于面向对象，这样开发组件和调试更方便</li>
</ul>
</li>
<li>缺点<ul>
<li>需要重新学习api</li>
<li>资源包大小增加（源码5000行左右）</li>
<li>容易与原生对象混淆：由于api与原生不同，混用的话容易出错</li>
</ul>
</li>
</ul>
<h3 id="immutable-js使用过程中的一些注意点"><a href="#immutable-js使用过程中的一些注意点" class="headerlink" title="immutable.js使用过程中的一些注意点"></a>immutable.js使用过程中的一些注意点</h3><ol>
<li><p>fromJS和toJS会深度转换数据，随之带来的开销较大，尽可能避免使用，单层数据转换使用Map()和List()</p>
</li>
<li><p>js是弱类型，但Map类型的key必须是string！</p>
</li>
<li><p>所有针对immutable变量的增删改必须左边有赋值，因为所有操作都不会改变原来的值，只是生成一个新的变量</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//javascript</span></span><br><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>];</span><br><span class="line">arr.push(<span class="number">5</span>);</span><br><span class="line"><span class="built_in">console</span>.log(arr) <span class="comment">//[1,2,3,4,5]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//immutable</span></span><br><span class="line"><span class="keyword">var</span> arr = immutable.fromJS([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>])</span><br><span class="line"><span class="comment">//错误用法</span></span><br><span class="line">arr.push(<span class="number">5</span>);</span><br><span class="line"><span class="built_in">console</span>.log(arr) <span class="comment">//[1,2,3,4]</span></span><br><span class="line"><span class="comment">//正确用法</span></span><br><span class="line">arr = arr.push(<span class="number">5</span>);</span><br><span class="line"><span class="built_in">console</span>.log(arr) <span class="comment">//[1,2,3,4,5]</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>引入immutablejs后，不应该再出现对象数组拷贝的代码</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//es6对象复制</span></span><br><span class="line"><span class="keyword">var</span> state = <span class="built_in">Object</span>.assign(&#123;&#125;, state, &#123;</span><br><span class="line">    key: value</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//array复制</span></span><br><span class="line"><span class="keyword">var</span> newArr = [].concat([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>])</span><br></pre></td></tr></table></figure>
</li>
<li><p>获取深层深套对象的值时不需要做每一层级的判空</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//javascript</span></span><br><span class="line"><span class="keyword">var</span> obj = &#123;<span class="attr">a</span>:<span class="number">1</span>&#125;</span><br><span class="line"><span class="keyword">var</span> res = obj.a.b.c   <span class="comment">//error</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//immutable</span></span><br><span class="line"><span class="keyword">var</span> immutableData=immutable.fromJS(&#123;<span class="attr">a</span>:<span class="number">1</span>&#125;)</span><br><span class="line"><span class="keyword">var</span> res = immutableData.getIn([<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>])  <span class="comment">//undefined</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>immutable对象直接可以转JSON.stringify(),不需要显式手动调用toJS()转原生</p>
</li>
<li>判断对象是否是空可以直接用size</li>
<li>调试过程中要看一个immutable变量中真实的值，可以chrome中加断点，在console中使用.toJS()方法来查看</li>
</ol>

                

                <hr>
                <!-- Pager -->
                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/2018/11/22/react-router/" data-toggle="tooltip" data-placement="top" title="react-router V4">&larr; Previous Post</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/2018/11/20/hello-world/" data-toggle="tooltip" data-placement="top" title="Hello World">Next Post &rarr;</a>
                        </li>
                    
                </ul>

                <br>
                
                <!-- require APlayer -->
                

                <!-- duoshuo Share start -->
                
                <!-- 多说 Share end-->

                <!-- 多说评论框 start -->
                
                <!-- 多说评论框 end -->

                <!-- disqus comment start -->
                
                <!-- disqus comment end -->

                

            </div>
            
            <!-- Tabe of Content -->
            <!-- Table of Contents -->

                
            <!-- Sidebar Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/tags/">FEATURED TAGS</a></h5>
                    <div class="tags">
                       
                    </div>
                </section>
                

                <!-- Friends Blog -->
                
                <hr>
                <h5>FRIENDS</h5>
                <ul class="list-inline">

                    
                        <li><a href="http://blog.csdn.net/123" target="_blank">CSDN 东方</a></li>
                    
                        <li><a href="http://dockone.io/people/123" target="_blank">掘金 东方</a></li>
                    
                        <li><a href="https://yq.aliyun.com/u/123" target="_blank">博客园 东方</a></li>
                    
                </ul>
                
            </div>
        </div>
    </div>
</article>










    <!-- Footer -->
    <!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                
                
                

                

                

                

                

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; eason.L 2018 
                    <br>
                    Theme by <a href="http://beantech.org">BeanTech</a> 
                    <span style="display: inline-block; margin: 0 5px;">
                        <i class="fa fa-heart"></i>
                    </span> 
                    re-Ported by <a href="https://github.com/eason1999">eason.L</a> | 
                    <iframe style="margin-left: 2px; margin-bottom:-5px;" frameborder="0" scrolling="0" width="91px" height="20px" src="https://ghbtns.com/github-btn.html?user=eason1999&repo=hexo-theme-huweihuang&type=star&count=true">
                    </iframe>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/hux-blog.min.js"></script>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->


<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("http://yoursite.com/js/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->




<!-- Baidu Tongji -->






	<a id="rocket" href="#top" class=""></a>
	<script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
    <script type="text/javascript" src="/js/toc.js?v=1.0.0" async=""></script>
<!-- Image to hack wechat -->
<img src="http://yoursite.com/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

</body>

</html>
